package model;

import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;

import view.GamePanel;

public class Snake extends Observable{
	public static final int UP=0X100;
	public static final int RIGHT=0X101;
	public static final int DOWN=0X102;
	public static final int LEFT=0X103;
	public static final int RUNNING=0X500;
	public static final int PASE=0X501;
	public static final int OVER=0X502;
	public static final int NOSTART=0X503;
	private LinkedList<Node> body;
	private int direction;
	private Node food;
	private int state;
	
	public Snake() {
		body=new LinkedList<>();
	}
	
	public void makeFood(){
		Random rd=new Random();
		int x=rd.nextInt(GamePanel.WIDTH/Node.WIDTH);
		int y=rd.nextInt(GamePanel.HEIGHT/Node.HEIGHT);
		food=new Node(x*Node.WIDTH, y*Node.HEIGHT);		
		setChanged();
		notifyObservers(food);
	}
	
	public void init() {
		direction=RIGHT;
		state=RUNNING;
		body.clear();
		body.addLast(new Node(80, 20));
		body.addLast(new Node(60, 20));
		body.addLast(new Node(40, 20));
		setChanged();
		notifyObservers(body);
		makeFood();
	}
	
	public boolean gameOver(){
		Node head=body.getFirst();
		int x=head.getX(),y=head.getY();
		if(x>480){ state=OVER;return true;}
		return false;
	}
	
	public void changeDirection(int direction){
		if(direction%2!=this.direction%2){
			this.direction=direction;
		}
	}
	
	private void move(){
		if(body.size()<3)return;
		
		Node tail=body.removeLast();
		Node head=body.getFirst();
		int x=head.getX(),y=head.getY();
		
		switch (direction) {
		case RIGHT:
			x=x+Node.WIDTH;
			break;
		case LEFT:
			x=x-Node.WIDTH;
			break;
		case UP:
			y=y-Node.HEIGHT;
			break;
		case DOWN:
			y=y+Node.HEIGHT;
			break;
		}
					
		tail.setX(x);
		tail.setY(y);
		body.addFirst(tail);
		if(gameOver())return;
		eat();
		setChanged();
		notifyObservers(body);
		
	}
	private void eat(){
		Node head=body.getFirst();
		if(head.getX()==food.getX()&&head.getY()==food.getY()){
			body.addLast(food);
			makeFood();
		}
		setChanged();
		notifyObservers(body);		
	}
	public void openMoveThread(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					System.out.println(state);
					if(state==RUNNING) 
						move();
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
